/*
 This file 'LoginApp' is part of Firebird Integrated Solution 1.0

 Copyright (c) 2014 Lincong

 Contact:  
 Email: lincong1987@gmail.com

 QQ: 159257119

 See Usage at http://www.jplatformx.com/firebird

 Create date: 2014-08-04 15:21
 */

define(function (require, exports, module) {

	require("dialog");
	require("base64");

	var $username = $("#username");
	var $password = $("#password");
	var $captcha = $("#captcha");
	var $captchaImage = $("#captcha_image");
	var $loginButton = $("#loginButton");
	var $regButton = $(".login-link div");

	var login = {
		url: {},
		message: {}
	};

	var replaceContextPath = function (path) {
		return $.trim(path).replace(/\{contextPath\}/g, firebird.api.get("contextPath").replace(/\/$/, ""));
	};

	login.url.login = "{contextPath}/security/user/login";
	login.url.show = "{contextPath}/security/user/show";
	login.url.captcha = "{contextPath}/captcha";
	login.url.success = "{contextPath}/fb-classic/main.jsp";
	login.message.logining = "登录中...";
	login.message.network_error = "网络异常";
	login.message.login = "登录";
	login.message.welcome = "欢迎回来!";
	login.message.login_success = "登录成功";
	login.message.login_error = "用户名或密码错误";

	login.showError = function (msg) {
		$(".login-error span").text(msg);
		$(".login-error").show();
		$loginButton.animate({
			top: 289
		}, 200);


		var timerId = null;
		var style = $(".login-error")[0].style,
			p = [4, 8, 4, 0, -4, -8, -4, 0],
			fx = function () {
				style.marginLeft = p.shift() + 'px';
				if (p.length <= 0) {
					style.marginLeft = 0;
					clearInterval(timerId);
				}
			};
		p = p.concat(p.concat(p.concat(p)));
		timerId = setInterval(fx, 16);

	};

	login.hideError = function () {
		$(".login-error span").text("");
		$(".login-button").animate({
			top: 245
		}, 200);
		$(".login-error").hide();
	};

	login.init = function (settings) {
		// mainHost = settings && settings.redirect || mainHost;
		this.checkLogin();
		this.bind();
	};

	login.checkLogin = function () {
		$.ajax({
			type: "post",
			url: replaceContextPath(login.url.show),
			success: function (json) {
				if (json.success === true) {
					$("#loginButton span").text(login.message.welcome);
					login.hideError();
					$.dialog.tips(login.message.welcome, 2000);
					setTimeout(function () {
						location.href = replaceContextPath(login.url.success);
					}, 2000);
				}
			}
		});
	};

	login.bind = function () {
		var me = this;
		$username.on("focus", function () {
			if ($(this).val() === 'Username') {
				$(this).val("");
			}
		}).on("blur", function () {
			if ($(this).val() === '') {
				$(this).val("Username");
			}
		});

		$password.on("focus", function () {
			if ($(this).val() === 'Password') {
				$(this).val("");
			}
		}).on("blur", function () {
			if ($(this).val() === '') {
				$(this).val("Password");
			}
		});

		$captcha.on("focus", function () {
			if ($(this).val() === "Captcha") {
				$(this).val("");
			}
		}).on("blur", function () {
			if ($(this).val() === "") {
				$(this).val("Captcha");
			}
		});

		$captchaImage.on("click", function (e) {
			$(this).attr({
				src: replaceContextPath(login.url.captcha) + "?_=" + new Date().getTime()
			});

			setTimeout(function () {
				$captcha.val("").focus();
			}, 0);
		});

		$username.on("keyup", function (e) {
			e = e || e.event;
			if (e.keyCode === 13) {
				$password.focus();
			}
		});
		$password.on("keyup", function (e) {
			e = e || e.event;
			if (e.keyCode === 13) {

				$captcha.length > 0 ? $captcha.focus() : me.doLogin();

			}
		});
		$captcha.length > 0 && $captcha.on("keyup", function (e) {
			e = e || e.event;
			if (e.keyCode === 13) {
				me.doLogin();
			}
		});

		$loginButton.on("click", function () {
			me.doLogin();
		});

		// $regButton.on("click", function (e) {
		// 	location.href = registerHost;
		// 	return e.preventDefault();
		// });

		var username = firebird.cookie.get("server.login.username");
		if (username !== "null") {
			$username.val(username);
		}

		$username.focus();
	};

	login.getParams = function (params) {
		return params;
	};

	login.doLogin = function () {

		if ($.trim($username.val()) === "" || $.trim($username.val()) === "Username") {
			login.showError("You forgot enter the username!");
			$username.focus();
			return;
		}

		if ($.trim($password.val()) === "" || $.trim($password.val()) === "Password") {
			login.showError("You forgot enter the password!");
			$password.focus();
			return;
		}

		if ($captcha.length > 0 && $.trim($captcha.val()) === "") {
			login.showError("You forgot enter the Captcha!");
			$captcha.focus();
			return;
		}

		firebird.cookie.set("jpx.username", $.trim($username.val()), {
			path: "/",
			expires: 3600 * 1000 * 24 * 7
		});

		$("#loginButton span").text("Send Data...");

		$.ajax({
			type: "post",
			url: replaceContextPath(login.url.login),

			data: login.getParams({
				name: $username.val(),
				password: $password.val(),
				captcha: $captcha.val()
			}),

			error: function () {
				login.showError("Network was bad.");
				$("#loginButton span").text("Log in");
			},
			success: function (json) {

				if (json.errMsg || json.errStack) {
					//$.dialog.error(json.errMsg);
					login.showError("ur username or password were incorrect.");
					$("#loginButton span").text("Log in");
					$("#captcha").val("");
					$("#captcha_image").attr({
						src: replaceContextPath(login.url.captcha) + "?_=" + new Date().getTime()
					});
					return;
				}
				if (json.success === true) {
					$("#loginButton span").text("Check in");
					setTimeout(function () {
						location.href = replaceContextPath(login.url.success);
					}, 2000);
				}
			}
		});
	};


	(function () {

		var tips = firebird.url.getParameter("tips");
		if (tips === "permission_error") {
			location.hash = "";
			$.dialog.tips("会话已失效，请重新登录。", 2000);
			return;
		}
		if (tips === "wait_u_back") {
			location.hash = "";
			$.dialog.tips("已退出。", 2000);
		}

		// $.ajax({
		// 	type: "post",
		// 	dataType: "json",
		// 	url: replaceContextPath(login.url.show),
		// 	success: function (json) {
		// 		if (json.success == true) {
		// 			$.dialog.tips(login.message.welcome, 2000);
		// 			setTimeout(function () {
		// 				location.href = replaceContextPath(login.url.success);
		// 			}, 2000);
		// 		}
		// 	}
		// });

		// login.checkLogin();

	})();

	setTimeout(function () {
		$username.focus().val($username.val());
	}, 0);

	module.exports = login;

});